package com.huahua.api.controller.common;

import com.huahua.api.enums.LocalDirEnum;
import com.huahua.api.exception.CommonException;
import com.huahua.api.util.CheckUtil;
import com.huahua.api.util.OwnFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.io.file.FileUtil;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author LoveHuaHua
 * @date 2025年03月01日 21:16
 * @description believe in yourself
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class DownloadController {

    /**
     * 下载
     *
     * @param dir      dir
     * @param fileName 文件名
     */
    @GetMapping("/download")
    public Mono<ResponseEntity<Resource>> download(String dir, String fileName) {
        return Mono.fromCallable(() -> {
            LocalDirEnum dirEnum = LocalDirEnum.getDir(dir);
            File file = OwnFileUtil.getDownloadPathFile(dirEnum, fileName);
            //正常下载目录
            String downloadBaseDir = FileUtil.normalize(OwnFileUtil.getDownloadBasePath(dirEnum));
            //目前下载目录
            String parentDir = FileUtil.normalize(file.getParent());
            //防止使用./等进行攻击
            CheckUtil.checkTrue(parentDir.equals(downloadBaseDir), new CommonException("请勿非法测试！"));

            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);

            Resource resource = new FileSystemResource(file);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8))
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        });
    }


}
